package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Autowired
    AuthorMapper authorMapper;
    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    String prefix;
    @Autowired
    ApArticleMapper apArticleMapper;

    /**
     * 生成文章静态页
     *
     * @param content
     * @param apArticle
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {

        try {
            //1.获取模版
            Template template = configuration.getTemplate("article.ftl");
            //2。准备数据
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            Integer userId = apAuthor.getUserId();

            Map map = new HashMap<>();
            map.put("article", apArticle);
            map.put("content", JSONArray.parseArray(content));
            map.put("authorApUserId", userId);
//3。将数据替换模版，输出到指定的输出流中
            StringWriter writer = new StringWriter();//字符串输出流
            template.process(map, writer);
            String contentHtml = writer.toString();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(contentHtml.getBytes());

            //4.将静态页上传到minio中
            String store = fileStorageService.store(prefix, apArticle.getId() + "html", "text/html", inputStream);

            //5.将minio中静态页面中的路径，设置到article表的static_url属性上
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页失败，当前文章信息", apArticle);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "生成静态页失败");
        }

    }
}
